
*** This file recreates Table 3 Panel D using recursive OOS

use mydata

rename *, lower

eststo clear

global ssize = _N

gen dm=mofd(date)
format dm %tm
tsset dm

* Taking lags of variables

gen l1mktrf = l1.mktrf
gen l1amihud =l1.amihud
gen l1tover = l1.tover
gen l1hml = l1.hml
gen l1smb = l1.smb


local train 120 // training period. 

// define flow variables 

gen yvar1 = f5.hfflow_ma // this is for moving average
gen yvar2 = hfflow_chg
gen yvar3 = f5.active_ma
gen yvar4 = active_chg

save oss_ma, replace

matrix OOS_T=J(3,4,.)

local x = 1

foreach flowvar in hfflow_ma hfflow_chg active_ma active_chg {

gen xvar = l1.`flowvar'
gen yvar = yvar`x'

local ctrlvar l1mktrf l1amihud l1tover l1hml l1smb 

matrix OOS_T[1,`x']=`x' 

local period `train'  
scalar define k = $ssize - `period' 
local y=k //the periods left for forcasting

gen yhat_a = .  // yhat of alternative model
gen yhat_n = .  // yhat of null model

forvalues i=1/`y' {

qui reg xvar `ctrlvar' if _n<= `period' +`i'  // recursive OSS
qui predict res_flow if  _n<= `period' +`i', re  // obtain residual flows 

qui reg yvar res_flow if _n< `period' +`i'  // flow variable on the past residual flows here...
qui replace yhat_a=_b[_cons] + _b[res_flow]*res_flow  if _n== `period' +`i'

qui su yvar if _n< `period' +`i'
qui replace yhat_n=r(mean) if _n== `period' +`i'
drop res_flow
}

*Sqaure of Predicted error (SE)
gen se_a = (yvar - yhat_a)^2
gen se_n = (yvar - yhat_n)^2

su se_a 
scalar define MSE_A = r(mean)
su se_n 
scalar define MSE_N = r(mean)

// OSS R2
dis "******************Training Period is `train'*******************************"
dis "OSS-R2:  " (1 - MSE_A/MSE_N) 
dis "***************************************************************************"
matrix OOS_T[2,`x']= (1 - MSE_A/MSE_N)*100


*** Clark and Weset (2007) t-test, bootstrap
gen CW = se_n - se_a + (yhat_n - yhat_a)^2

qui reg CW , vce(bootstrap, rep(1000))
matrix OOS_T[3,`x']=_b[_cons]/_se[_cons]

local ++x
use oss_ma, clear

}


mat rownames OOS_T = Flowvar OOS-R2(%) OOS-T_CWbs 
matrix list OOS_T, format(%9.3f)

putexcel set T3D, sheet(PanelD) modify
putexcel A1=matrix(OOS_T), names
